package cn.common.controller;

/**
 * Copyright
 *
 * @Author WuHuang
 * @Date 2022/12/21
 */


import cn.common.RetryWorkerService;
import cn.common.dto.RetryRequestParamDTO;
import cn.common.exceptions.BasicRetryException;
import cn.common.util.ApplicationContextUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.util.config.HttpResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeoutException;

@RestController
@RequestMapping({"/api/v1/tx/retry"})
@Api("重试callback统一入口")
public class RetryCallBackController {
    private static final Logger log = LoggerFactory.getLogger(RetryCallBackController.class);

    public RetryCallBackController() {
    }

    @PostMapping({"/callback"})
    @ApiOperation("重试回调")
    public HttpResult<Boolean> callBack(@RequestBody RetryRequestParamDTO retryRequestParamDTO) {
        try {
            log.info("RetryCallBackController,重试回调..{}", JSON.toJSONString(retryRequestParamDTO));
            Class requestBodyClass = Class.forName((String)retryRequestParamDTO.getMetaMap().get("basicRetry_requestBodyBeanName"));
            Object obj = JSONObject.parseObject(JSONObject.toJSONString(retryRequestParamDTO.getRequestBody()), requestBodyClass);
            retryRequestParamDTO.setRequestBody(obj);
            String workBeanName = (String)retryRequestParamDTO.getMetaMap().get("basicRetry_workBeanName");
            Class clazz = Class.forName(workBeanName);
            RetryWorkerService retryWorkerService = (RetryWorkerService) ApplicationContextUtil.getBean(clazz);
            retryWorkerService.doWork(retryRequestParamDTO);
        } catch (BasicRetryException var7) {
            log.error("callBack basicretryerror request={}", JSON.toJSONString(retryRequestParamDTO), var7);
            return HttpResult.fail(var7.getMessage());
        } catch (TimeoutException var8) {
            log.error("callBack timeouterror request={}", JSON.toJSONString(retryRequestParamDTO), var8);
            return HttpResult.fail(var8.getMessage());
        } catch (Exception var9) {
            log.error("callBack exceptionerror request={}", JSON.toJSONString(retryRequestParamDTO), var9);
        }

        return HttpResult.succ(Boolean.TRUE);
    }
}

